package com.hfi.ood.payroll.classification;

import com.hfi.ood.payroll.domain.Paycheck;
import com.hfi.ood.payroll.domain.PaymentClassification;
import com.hfi.ood.payroll.domain.TimeCard;
import lombok.Builder;
import lombok.Data;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;

import java.math.RoundingMode;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ChangLiang
 * @date 2020/5/19
 */
@Data
@Builder
public class HourlyClassification implements PaymentClassification {

    /**
     * 时薪
     */
    private Money rate;

    private Map<Date, TimeCard> timeCards;

    @Override
    public Money calculatePay(Paycheck paycheck) {
        Money totalPay = Money.of(CurrencyUnit.of("CNY"), 0);
        try {
            totalPay =  Money.total(timeCards.values().stream().filter(tc -> tc.getDate().before(paycheck.getPayPeriodEnd())
                    && tc.getDate().after(paycheck.getPayPeriodStart())).map(tc -> calculatePayForTimeCard(tc)).collect(Collectors.toList()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return totalPay;
    }

    private Money calculatePayForTimeCard(TimeCard timeCard) {
        int hours = timeCard.getHours();
        return hours > 8 ?
                rate.multipliedBy(8L)
                        .plus(rate.multipliedBy(1.5, RoundingMode.UNNECESSARY).multipliedBy(hours - 8)):
                rate.multipliedBy(8L);
    }
}
